package com.simple.crawler.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

    public static String getId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getId(int limit) {
        return getId().substring(0, limit + 1);
    }

    public static boolean isNull(String str) {
        return str == null;
    }

    public static boolean isBlank(String str) {
        return str == null || str.length() == 0;
    }

    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    public static String toArrJson(Object[] arr) {
        if (arr == null || arr.length == 0) {
            return "[]";
        }
        return JSONArray.toJSONString(arr);
    }

    public static String toObjJson(Object obj) {
        if (obj == null) {
            return "{}";
        }
        return JSONObject.toJSONString(obj);
    }

    public static Number convertToNumber(String str, Class<?> type) {
        if (Integer.class.equals(type)) {
            return Integer.parseInt(str);
        }
        if (Float.class.equals(type)) {
            return Float.parseFloat(str);
        }
        if (Double.class.equals(type)) {
            return Double.parseDouble(str);
        }
        if (Long.class.equals(type)) {
            return Long.parseLong(str);
        }
        return 0;
    }

    public static <T> T convertToObj(String str, Class<T> type) {
        return JSONObject.parseObject(str, type);
    }

    public static <T> List<T> convertToList(String str, Class<T> type) {
        return JSONArray.parseArray(str, type);
    }

        public static String getMatchObj(String target, String expr) {
        return getMatchObj(target, expr, 1);
    }

    public static String getMatchObj(String target, String expr, int index) {
        if (isBlank(target)) {
            return "";
        }
        Pattern pattern = Pattern.compile(expr);
        Matcher matcher = pattern.matcher(target);
        if (matcher.matches()) {
            return matcher.group(index);
        }
        return "";
    }
    public static List<String> getMatchList(String target, String expr) {
        List<String> targetList = new ArrayList<>();
        if (isBlank(target)) {
            return targetList;
        }
        Pattern pattern = Pattern.compile(expr);
        Matcher matcher = pattern.matcher(target);
        while (matcher.find()) {
            targetList.add(matcher.group(1));
        }
        return targetList;
    }

    public static boolean isContains(String str, String target) {
        if (isBlank(str)) {
            return false;
        }
        return str.indexOf(target) != -1;
    }

}
